package Sort;

import java.util.Arrays;

/**
 * @Author: 吕庆龙
 * @Date: 2019/9/30 16:35
 * <p>
 * 功能描述: 希尔排序
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        int[] arr2 = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        System.out.println("希尔排序交换法");
        shellSort(arr);
        System.out.println("希尔排序移位法");
        shellSort2(arr2);
    }

    /**
     * 功能描述: 希尔排序交换法
     */
    public static void shellSort(int[] a) {
        int temp = 0;
        int count = 1;
        for (int gap = a.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < a.length; i++) {
                for (int j = i - gap; j >= 0; j -= gap) {
                    if (a[j + gap] < a[j]) {
                        temp = a[j + gap];
                        a[j + gap] = a[j];
                        a[j] = temp;
                    }
                }
            }
            System.out.println("第" + (count++) + "趟排序=" + Arrays.toString(a));
        }
    }

    /**
     * 功能描述: 希尔排序移位法,这个才有点直接插入排序的的影子,
     * {8, 9, 1, 7, 2, 3, 5, 4, 6, 0}
     */
    public static void shellSort2(int[] a) {
        int temp = 0;
        int j = 0;
        int count = 1;
        for (int gap = a.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < a.length; i++) {
                temp = a[i];
                j = i;  //还有这里不能是j=gap。第一次写错了
                if (a[j] < a[j - gap]) {
                    //注意是temp < a[j - gap]而不是a[j] < a[j - gap]。这个地方第一次写错了
                    while (j - gap >= 0 && temp < a[j - gap]) {
                        a[j] = a[j - gap];
                        j = j - gap;
                    }
//                    a[j] = temp;
                }
                a[j] = temp;
            }
            System.out.println("第" + (count++) + "趟排序=" + Arrays.toString(a));
        }
    }
}
